define(function (require, exports) {
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util = require('util');
	var view = require('@base/view');
	var dspUtil = require('dspUtil');

	var _convertMapToItems = dspUtil._convertMapToItems;
	exports.convertMapToItems = _convertMapToItems;
	var BID_TYPE = pubjs.config("CONST/BID_TYPE");

	// raido值定义
	var RAIDO_VALUE_DEFINE = pubjs.config('RAIDO_VALUE_DEFINE');

	// 出价方式候选项配置
	var CHARGE_TYPE_OPTS = [
		 {value: 0, label: LANG("竞价CPM"), access: 'campaign.cpm_bid'}
		,{value: 1, label: LANG("CPA优化"), access: 'campaign.cpa_opt'}
		,{value: 2, label: LANG("CPC优化"), access: 'campaign.cpc_opt'}
		,{value: 3, label: LANG("固定CPC"), access: 'campaign.cpc_fix'}
		// ,{value: 4, label: LANG("固定CPM"), access: 'campaign.cpm_fix'}
	];

	var CHARGE_TEXT = {
		0: LANG('目标CPM')
		,1: LANG('目标CPA')
		,2: LANG('目标CPC')
		,3: LANG('结算CPC')
		// ,4: LANG('结算CPM')
	};

	// 出价方式候选项配置
	var BID_TYPE_OPTS = [
		{value: BID_TYPE.PUBLIC, label: LANG("公开竞价")}
		,{value: BID_TYPE.PDB, label: LANG("PDB")}
		,{value: BID_TYPE.PREFER, label: LANG("首选交易")}
		,{value: BID_TYPE.PRIVATE, label: LANG("私下竞价")}
	];

	var Base = view.container.extend({
		init: function(config) {
			var rvd = RAIDO_VALUE_DEFINE;


			config = pubjs.conf(config, {
				'class': 'P-campaignSetting',
				'tplFile': '/tpl/campaign/editStep/set.tpl',
				'vModel': {
					'_BidTypeOpts': BID_TYPE_OPTS,
					'_ChargeTypeOpts': CHARGE_TYPE_OPTS,

					'BidType': BID_TYPE_OPTS[0].value,
					'ChargeType': CHARGE_TYPE_OPTS[0].value,

					'ChargeText': CHARGE_TEXT[0],

					'Price': '0.00',
					'TopPrice': '0.00',

					'AlgorithmModel': 1,

					'OrderPriority': 0,

					'GovernorStatus': 1,

					'ImpressionMonitor': '',
					'ClickMonitor': '',

					'Status': 1,

					'_frequencyRadio': rvd.ALL,
					'_MonitorRadio': rvd.ALL,
					'monitorPlaceholder': LANG('请输入监控的第三方调用的 URL 地址，暂不支持互众和腾讯渠道，多个 URL 地址请用回车换行隔开'),

					'vmClickSelectOrder': this.eventClickSelectOrder,

					// 权限点
					'right': {
						bidType: pubjs.checkRight(''),
						chargeType: pubjs.checkRight(''),
						algorithmModel: pubjs.checkRight(''),
						frequency: pubjs.checkRight(''),
						monitor: pubjs.checkRight(''),
						campaignMonitor: pubjs.checkRight('')
					}

				},
				// tips配置
				'tipOpts': {
					'algorithmModelTip': {
						'width': 400,
						'data': LANG('模型 A：算法优化出价使得最终结果会尽可能接近目标值 (建议)\n模型 B：不优化出价，最终结果就是目标值 (不建议)')
					},
					'orderPriorityTip': {
						'width': 400,
						'data': LANG('数值越大订单优先级越高，系统将选择优先级高进行展示，相同优先级将随机分配')
					},
					'frequencyTip': {
						'width': 400,
						'data': LANG('控制在设定的时间内推广组或创意包的展现次数。“0”表示不限次数。多个条件控制的情况，只要满足任意一个条件则暂停对应创意包或推广组的投放。')
					}
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			var vm = self.vm.$;
			self.getDOM().addClass(c.class);


			var opts = {
				'algorithmModel': {
					'type': 'button',
					'options': [
						{id:1, name: LANG('模型A')},
						{id:2, name: LANG('模型B')}
					],
					'value': 1,
					'width': 200,
					'panel_config': {
						'hasSearch': false
					}
				},
			};

			self.buildFromTemplate(util.extend(opts, c.tipOpts));

			self.vm.watch('BidType', self.watchBidTypeChange);
			self.vm.watch('ChargeType', self.watchChargeTypeChange);
		},
		beforeBuildTemplate: function(){

		},
		afterBuildTemplate: function(){
			pubjs.core.cast('campaignBidTypeChange', this.vm.$.BidType);
		},
		watchBidTypeChange: function(last){
			pubjs.core.cast('campaignBidTypeChange', last);
		},
		watchChargeTypeChange: function(last){
			this.vm.$.ChargeText = CHARGE_TEXT[last];
		},
		onDropChange: function(ev){
			if(ev.name == 'algorithmModel'){
				this.vm.$.AlgorithmModel = ev.param.id;
			}
		},
		onSelectOrderSuccess: function(ev){
			this.renderOrder(ev.param);
			pubjs.core.cast('campaignSelectOrderSuccess', ev.param);
			return false;
		},
		renderOrder: function(data){
			var el = this.getDOM();
			var selectOrder = el.find('.selectOrder');
			if(data && data.length){
				selectOrder.text(LANG('已选订单')+'('+data.length+')');
			}else {
				selectOrder.text(LANG('选择订单'));
			}

			this.$selectOrder = data || [];
		},
		eventClickSelectOrder: function(ev){
			var self = this;
			var pop = self.get('selectOrder');
			var param = {'Type': self.vm.$.BidType};

			if(!pop){
				self.createAsync('selectOrder', 'campaign/popwin/selectOrder.main', {
				}, function(mod){
					if(mod){
						mod.setParam(param, true).show().load();
						if(self.$selectOrder && self.$selectOrder.length) {
							mod.setData(self.$selectOrder);
						}
					}
				});
			}else{
				pop.reset().setParam(param, true).show().load().setData(self.$selectOrder);
			}

		},
		validate: function(data){
			var self = this;
			data = data || self.getData();
			if (data) {

			}

			return true;
		},
		setData: function(data){
			var self = this;
			var vm = self.vm.$;
			var cs = self.$;
			var rvd = RAIDO_VALUE_DEFINE;

			if(data){
				vm.BidType = data.MainStrategy.BidType;
				vm.ChargeType = data.MainStrategy.Bid.Way;
				vm.Price = data.MainStrategy.Bid.Price;

				if(self.get('algorithmModel')){
					self.$.algorithmModel.setValue(data.MainStrategy.Bid.OptimizeMode);
				}

				vm.TopPrice = data.MainStrategy.Bid.TopCpm;

				if(data.MainStrategy.Deal && data.MainStrategy.Deal.Ids) {
					self.renderOrder(data.MainStrategy.Deal.Ids);
					vm.OrderPriority = data.MainStrategy.Deal.Priority;
				}

				vm.GovernorStatus = data.GovernorStatus;


				var frequency = data.MainStrategy.FrequencyFilters || [];
				vm._frequencyRadio = frequency.length ? rvd.NOT_ALL: rvd.ALL;
				if(cs.frequency){
					cs.frequency.setData(frequency);
				}

				if(data.ThirdMonitor && data.ThirdMonitor.Exposure){
					vm.ImpressionMonitor = data.ThirdMonitor.Exposure.join('\n');
				}
				if(data.ThirdMonitor && data.ThirdMonitor.Click){
					vm.ClickMonitor = data.ThirdMonitor.Click.join('\n');
				}

				if(vm.ImpressionMonitor || vm.ClickMonitor){
					vm._MonitorRadio = rvd.NOT_ALL;
				}else{
					vm._MonitorRadio = rvd.ALL;
				}

				if(data.Monitor){
					cs.campaignMonitor.setData(data.Monitor);
				}

				vm.Status = data.Status;

			}

			return self;
		},
		getData: function(){
			var self = this;
			var vm = self.vm.$;
			var ALL   = RAIDO_VALUE_DEFINE.ALL;
			var data = {};

			// 活动类型
			data.MainStrategy = {};

			data.MainStrategy.BidType = vm.BidType;
			if(~[BID_TYPE.PREFER, BID_TYPE.PDB].indexOf(+vm.BidType)) {
				// 订单
				var ids = [];
				util.each(self.$selectOrder || [], function(item){
					if(item){
						ids.push(item);
					}
				});
				data.MainStrategy.Deal = {Ids: ids};
				// 订单优先级
				data.MainStrategy.Deal.Priority = vm.OrderPriority;
			}
			else {
				data.MainStrategy.Bid = {
					// 出价方式
					Way: vm.ChargeType,
					// 出价
					Price: vm.Price,
					// 最高cpm
					TopCpm: vm.TopPrice,
					// 算法模型
					OptimizeMode: self.$.algorithmModel.getValue(true).id
				};
			}

			// 投放速度
			data.GovernorStatus = vm.GovernorStatus;

			// 频次控制
			if(vm._frequencyRadio != ALL){
				data.MainStrategy.FrequencyFilters = self.$.frequency.getData();
			}

			// 三方监测
			if(vm._MonitorRadio != ALL){

				var ImpressionMonitor = [];
				var ClickMonitor = [];

				var murl = vm.ImpressionMonitor.replace(/[\r\n]+/g, '\n').split('\n');
				util.each(murl, function(item){
					if(util.trim(item)){
						ImpressionMonitor.push(util.trim(item));
					}
				});

				var murl = vm.ClickMonitor.replace(/[\r\n]+/g, '\n').split('\n');
				util.each(murl, function(item){
					if(util.trim(item)){
						ClickMonitor.push(util.trim(item));
					}
				});

				data.ThirdMonitor = {
					Exposure: ImpressionMonitor,
					Click: ClickMonitor
				}
			}

			// 智能监控
			data.Monitor = self.$.campaignMonitor.getData();

			// 状态
			data.Status = +vm.Status;


			return data;
		},
		reset: function(){
			var self = this;
			self.vm.reset();
			self.$selectOrder = [];
			if(self.get('algorithmModel')){
				self.$.algorithmModel.reset();
			}
			if(self.get('frequency')){
				self.$.frequency.reset();
			}
			if(self.get('campaignMonitor')){
				self.$.campaignMonitor.reset();
			}
			self.renderOrder();

			return self;
		}

	});

	exports.base = Base;

})